'use strict';
const moment = require('moment');
const conn = require('../../../server/libs/DB/meter/asycnPool').pool;
const redisClient = require('../../../server/libs/Redis/redisClient').client;
const _ = require('underscore');
const {checkInvalidNum} = require('../../../server/libs/Utils');

//const log = require('../../server/libs/SysLog/Write').log;

function flowCalculation(date) {
    /**
     *计算各个线路每日用电量
     *
     * */
    let taskDate = date ? moment(date) : moment().subtract(1, 'days');//判断是否有日期参数，未传参则计算前一天的数据（自动任务执行），传参的话计算传入日期的数据
    let currentDate = taskDate.format('YYYY-MM-DD');//设置任务截止日期
    let lastDate = taskDate.subtract(1, 'days').format('YYYY-MM-DD');//设置任务起始日期

    conn.query('SELECT df.device_no,df.device_addr,df.station_id FROM device_file df WHERE df.`delete_sign`=1', function (err, deviceList) {
        //console.log(deviceList);
        let stationGroup = _.groupBy(deviceList, 'station_id');
        _.forEach(stationGroup, function (stationDeviceList, key) {
            let flowDataTable = `flow_day_${key}`;
            let getFlowDataSql = `SELECT * FROM ${flowDataTable} fd WHERE fd.data_date= ? `;
            conn.query(getFlowDataSql, [lastDate], function (err, FlowData) {
                _.forEach(stationDeviceList, function (device) {
                    let deviceDataKey = `${device.device_no}-${device.device_addr}`;
                    let redisDeviceDataKey = `${deviceDataKey}-${currentDate}`;
                    let matchDataList = _.filter(FlowData, {device_no: deviceDataKey});
                    redisClient.lrange(redisDeviceDataKey, -1, -1, function (err, plc_data) {//查看最后一条数据
                        try {
                            if (plc_data && plc_data.length) {
                                let current_data_str = plc_data.shift();
                                let current_data = JSON.parse(current_data_str);
                                let cumFlow = current_data.cumFlow;
                                let totalCumFlow;
                                if (matchDataList && matchDataList.length) {
                                    let matchData = matchDataList.shift();
                                    if (checkInvalidNum(matchData.total_cumflow)) totalCumFlow = matchData.total_cumflow;
                                }
                                let dayCumflow = checkInvalidNum(totalCumFlow) ? cumFlow - totalCumFlow : null;
                                let insertObj = {
                                    device_no: deviceDataKey,
                                    data_date: currentDate,
                                    total_cumflow_time: current_data.currentTime,
                                    total_cumflow: cumFlow,
                                    day_cumflow: dayCumflow >= 0 ? dayCumflow : 0
                                };
                                let insertSql = `INSERT INTO ${flowDataTable} SET ? ON DUPLICATE KEY UPDATE ?`;
                                conn.query(insertSql, [insertObj, insertObj], function (err) {
                                    if (err) console.log(err);
                                });
                            } else {
                            }
                        } catch (e) {
                            console.log(e);
                        }
                    });
                });
            });
        })
    });
}

module.exports = flowCalculation;